const db = require('../public/javascripts/mongodb');
const format = require('../public/javascripts/format')();
const config = require('../public/javascripts/mongodb.config')
const router = require('koa-router')();
//const koaBody = require('koa-body')

router.post('/mongo/test', async (ctx) => {
    let req = JSON.parse(ctx.request.body);
    const output = { "a": 1 };
    ctx.set('Content-Type', 'application/json');
    //ctx.body = query;
    //console.log(JSON.stringify(ctx.request.body));
    return (ctx.response.body = JSON.stringify(output));
    //return ctx.response.body = {response:'yes'};
});

/**
 * db:"jd"
 * collection:"comments"
 * time1: date(yyyy-MM-dd HH:mm:ss)
 * time2: date
 */
router.post('/mongo/find', async (ctx) => {
    ctx.set('Content-Type', 'application/json');
    let output = {};
    try {
        let req = typeof (ctx.request.body) == 'string' ? JSON.parse(ctx.request.body) : ctx.request.body;
        if (config[req.db]) {
            if (config[req.db][req.collection]) {
                let params = {};
                if (req.collection == "comments") {
                    params = {
                        $and: [{ referenceTime: { $gt: req.time1 } }, { referenceTime: { $lte: req.time2 } }]
                    }
                }
                else if (req.collection == "items") {
                    params = { 'shopId': req.shopId.toString() };
                }
                if (req.skuId && req.skuId != '') {
                    params.$and.push({ 'skuId': req.skuId });
                }
                output[req.collection] = await db.find(config[req.db][req.collection], params).catch(error => { throw (error); });
                let a = 1;
            }
        }
        else {
            throw (`参数有误！`);
        }
    }
    catch (error) {
        output = { error: error.toString() };
    }
    //     //ctx.body = query;
    //console.log(JSON.stringify(ctx.request.body));
    return (ctx.response.body = JSON.stringify(output));
});
/**
 * 分页查询
 * 
 */
router.post('/mongo/findPaged', async (ctx) => {
    ctx.set('Content-Type', 'application/json');
    let output = {};
    try {
        let req = typeof (ctx.request.body) == 'string' ? JSON.parse(ctx.request.body) : ctx.request.body;
        if (config[req.db]) {
            if (config[req.db][req.collection]) {
                let params = {};
                let array = [];
                let allow = ["skuId", "create1", "create2", "score"];
                for (let key of allow) {
                    if (req[key] && req[key] != "") {
                        if (key == "skuId") {
                            array.push({ "skuId": req[key].toString() });
                        }
                        else if (key == "create1") {
                            array.push({ "create": { "$gte": new Date(req[key]).format("yyyy-MM-dd HH:mm:ss") } });
                        }
                        else if (key == "create2") {
                            array.push({ "create": { "$lte": new Date(req[key]).format("yyyy-MM-dd HH:mm:ss") } });
                        }
                        else if (key == "score") {
                            array.push({ "score": parseInt(req[key]) });
                        }
                    }
                }
                if (array.length > 0) {
                    params = { "$and": array };
                }
                //output["params"] = params; 
                let skip = Number(req.skip ? req.skip : 0);
                let limit = Number(req.limit ? req.limit : 0);
                if (Number.isNaN(skip) || Number.isNaN(limit)) {
                    throw (`参数有误！`);
                }
                output[req.collection] = await db.findPaged(config[req.db][req.collection], params, skip, limit).catch(error => { throw (error); });
            }
        }
        else {
            throw (`参数有误！`);
        }
    }
    catch (error) {
        output = { error: error.toString() };
    }
    //     //ctx.body = query;
    //console.log(JSON.stringify(ctx.request.body));
    return (ctx.response.body = JSON.stringify(output));
})
/**
 * 查询表行数
 */
router.post('/mongo/count', async (ctx) => {
    ctx.set('Content-Type', 'application/json');
    let output = {};
    try {
        let req = typeof (ctx.request.body) == 'string' ? JSON.parse(ctx.request.body) : ctx.request.body;
        if (config[req.db]) {
            if (config[req.db][req.collection]) {
                let params = {};
                let array = [];
                let allow = ["skuId", "changeTime1", "changeTime2", "create1", "create2", "score"];
                for (let key of allow) {
                    if (req[key] && req[key] != "") {
                        if (key == "skuId") {
                            array.push({ "skuId": req[key].toString() });
                        }
                        else if (key == "changeTime1") {
                            array.push({ "changeTime": { "$gte": new Date(req[key]).format("yyyy-MM-dd HH:mm:ss") } });
                        }
                        else if (key == "changeTime2") {
                            array.push({ "changeTime": { "$lte": new Date(req[key]).format("yyyy-MM-dd HH:mm:ss") } });
                        }
                        else if (key == "create1") {
                            array.push({ "create": { "$gte": new Date(req[key]).format("yyyy-MM-dd HH:mm:ss") } });
                        }
                        else if (key == "create2") {
                            array.push({ "create": { "$lte": new Date(req[key]).format("yyyy-MM-dd HH:mm:ss") } });
                        }
                        else if (key == "score") {
                            array.push({ "score": parseInt(req[key]) });
                        }
                    }
                }
                if (array.length > 0) {
                    params = { "$and": array };
                }
                output[req.collection] = await db.count(config[req.db][req.collection], params)
                    .catch(error => { throw (error); });
            }
        }
        else {
            throw (`参数有误！`);
        }
    }
    catch (error) {
        output = { error: error.toString() };
    }
    return (ctx.response.body = JSON.stringify(output));
});
/**
 * 下载文件
 * 
 */
const send = require('koa-send');
const fs = require('fs');

router.get('/mongo/export', async (ctx) => {
    let date = ctx.query.date;
    let fileName = ctx.query.file;
    let path = `./public/mongoExport/${date}`;
    let names = fs.readdirSync(path);
    if (names.includes(`${fileName}.json`)) {
        ctx.attachment(`${path}/${fileName}.json`);
        await send(ctx, `${path}/${fileName}.json`);
    };
})
/**
 * 编辑summary 内容
 * 
 */
router.post('/mongo/summary/edit', async (ctx) => {
    ctx.set('Content-Type', 'application/json');
    try {
        let req = typeof (ctx.request.body) == 'string' ? JSON.parse(ctx.request.body) : ctx.request.body;
        if (req.skuId) {
            let skuId = req.skuId.toString();
            let where = { 'skuId': skuId };
            let count = 0;
            count = await db.count(config.jd.summary, where).catch(error => { throw error; });
            if (count == 0) {
                throw (`不存在的skuId`);
            }
            let editParams = {};
            let allowEdit = ['cs_name', 'cs_brand', 'disabled'];
            for (let key of allowEdit) {
                if (req[key]) {
                    editParams[key] = req[key].toString();
                }
            }
            if (editParams != {}) {
                let result = await db.updateMany(config.jd.summary, where, editParams).catch(error => { throw error; });
            }
            output = { ...{ 'result': 'success' }, ...editParams };
        }
        else {
            throw (`需要skuId`);
        }
    }
    catch (error) {
        output = { 'result': 'error', 'error': error.toString() };
    }
    return (ctx.response.body = JSON.stringify(output));
})
router.post('/mongo/summary/add', async (ctx) => {
    ctx.set('Content-Type', 'application/json');
    try {
        let req = typeof (ctx.request.body) == 'string' ? JSON.parse(ctx.request.body) : ctx.request.body;
        if (req.skuId) {
            let skuId = req.skuId.toString();
            let count = 1;
            count = await db.count(config.jd.summary, { 'skuId': skuId }).catch(error => { throw error; });
            if (count > 0) {
                throw (`已存在的skuId`);
            }
            let addParams =
            {
                "skuId": skuId,
                "cs_name": "",
                "cs_brand": "",
                "fetch_name": "",
                "fetch_exbrand": "exbrand_16407",
                "fetch_brand": "",
                "fetch_categoryCN": "",
                "fetch_title": "",
                "callback": "",
                "goodRate": "",
                "commentCount": 0,
                "defaultGoodCount": 0,
                "score1Count": 0,
                "score2Count": 0,
                "score3Count": 0,
                "score4Count": 0,
                "score5Count": 0,
                "videoCount": 0,
                "imageListCount": 0,
                "showCount": 0,
                "fixCount": 0,
                "afterCount": 0,
                "disabled": "",
                "firstCategory": "",
                "secondCategory": "",
                "thirdCategory": "",
                "comments_maxId": "",
                "changeTime": "",
                "ZTmark": "",
                "categoryCN": "",
                "exbrand": "",
                "createTime": new Date().format("yyyy-MM-dd HH:mm:ss")
            };
            let allowAdd = ['cs_name', 'cs_brand', 'disabled'];
            for (let key of allowAdd) {
                if (req[key]) {
                    addParams[key] = req[key].toString();
                }
            }
            let result = await db.insertOne(config.jd.summary, addParams).catch(error => { throw error; });
            output = { 'result': 'success' };
        }
        else {
            throw (`需要skuId`);
        }
    }
    catch (error) {
        output = { 'result': 'error', 'error': error.toString() };
    }
    return (ctx.response.body = JSON.stringify(output));
})
router.post('/mongo/summary/delete', async (ctx) => {
    ctx.set('Content-Type', 'application/json');
    try {
        let req = typeof (ctx.request.body) == 'string' ? JSON.parse(ctx.request.body) : ctx.request.body;
        if (req.skuId) {
            let skuId = req.skuId.toString();
            let count = 1;
            count = await db.count(config.jd.summary, { 'skuId': skuId }).catch(error => { throw error; });
            if (count == 0) {
                throw (`不存在的skuId`);
            }
            let result = await db.deleteMany(config.jd.summary, { 'skuId': skuId }).catch(error => { throw error; });
            output = { 'result': 'success', 'message': `已删除${count}条记录！` };
        }
        else {
            throw (`需要skuId`);
        }
    }
    catch (error) {
        output = { 'result': 'error', 'error': error.toString() };
    }
    return (ctx.response.body = JSON.stringify(output));
})

/**
 * 编辑shops 内容
 * 
 */
router.post('/mongo/shops/edit', async (ctx) => {
    ctx.set('Content-Type', 'application/json');
    try {
        let req = typeof (ctx.request.body) == 'string' ? JSON.parse(ctx.request.body) : ctx.request.body;
        if (req.shopId) {
            let shopId = req.shopId.toString();
            let where = { 'shopId': shopId };
            let count = 0;
            count = await db.count(config.jd.shops, where).catch(error => { throw error; });
            if (count == 0) {
                throw (`不存在的shopId`);
            }
            let editParams = {};
            let allowEdit = ['disabled', 'keywords', 'everyFewDays'];
            for (let key of allowEdit) {
                if(req[key]){
                    if (key == 'keywords') {
                        editParams[key] = Array.from(new Set(req[key].toString().split(',')));
                    }
                    else if (key == 'everyFewDays') {
                        editParams[key] = parseInt(Number(editParams[key]));
                    }
                    else {
                        editParams[key] = req[key].toString();
                    }
                }
            }
            if (editParams != {}) {
                let result = await db.updateMany(config.jd.shops, where, editParams).catch(error => { throw error; });
            }
            output = { 'result': 'success', 'params': editParams };
        }
        else {
            throw (`需要shopId`);
        }
    }
    catch (error) {
        output = { 'result': 'error', 'error': error.toString() };
    }
    return (ctx.response.body = JSON.stringify(output));
})
router.post('/mongo/shops/add', async (ctx) => {
    ctx.set('Content-Type', 'application/json');
    try {
        let req = typeof (ctx.request.body) == 'string' ? JSON.parse(ctx.request.body) : ctx.request.body;
        if (req.shopId) {
            let shopId = req.shopId.toString();
            let keywords = Array.from(new Set(req['keywords'].toString().split(',')));
            let everyFewDays = req['everyFewDays'] ? parseInt(Number(req['everyFewDays'])) : 1;
            let count = 1;
            count = await db.count(config.jd.shops, { 'shopId': shopId }).catch(error => { throw error; });
            if (count > 0) {
                throw (`已存在的skuId`);
            }
            let addParams =
            {
                "shopId": shopId,
                'keywords': keywords,
                "changeTime": "",
                "create": new Date().format("yyyy-MM-dd HH:mm:ss"),
                "title": "",
                "url": "",
                "disabled": "",
                "everyFewDays": everyFewDays
            };
            let result = await db.insertOne(config.jd.shops, addParams).catch(error => { throw error; });
            output = { 'result': 'success', 'prarms': addParams };
        }
        else {
            throw (`需要shopId`);
        }
    }
    catch (error) {
        output = { 'result': 'error', 'error': error.toString() };
    }
    return (ctx.response.body = JSON.stringify(output));
})
router.post('/mongo/shops/delete', async (ctx) => {
    ctx.set('Content-Type', 'application/json');
    try {
        let req = typeof (ctx.request.body) == 'string' ? JSON.parse(ctx.request.body) : ctx.request.body;
        if (req.shopId) {
            let shopId = req.shopId.toString();
            let count = await db.count(config.jd.shops, { 'shopId': shopId }).catch(error => { throw error; });
            if (count == 0) {
                throw (`不存在的skuId`);
            }
            let result = await db.deleteMany(config.jd.shops, { 'shopId': shopId }).catch(error => { throw error; });
            output = { 'result': 'success', 'message': `已删除${count}条记录！` };
        }
        else {
            throw (`需要shopId`);
        }
    }
    catch (error) {
        output = { 'result': 'error', 'error': error.toString() };
    }
    return (ctx.response.body = JSON.stringify(output));
})

//取logId最大值
router.post('/mongo/shops/log/max', async (ctx) => {
    ctx.set('Content-Type', 'application/json');
    try {
        let result = await db.groupMax(config.jd.shopsLog, {}, 'logId').catch(error => { throw error; });
        output = { 'result': 'success', 'logId': result };
    }
    catch (error) {
        output = { 'result': 'error', 'error': error.toString() };
    }
    return (ctx.response.body = JSON.stringify(output));
});
//综合log&error 判断当前操作是否完成
router.post('/mongo/comments/isCrawling', async (ctx) => {
    let output = {};
    try {
        let max = await db.groupMax(config.jd.log, { operation: 'crawl' }, 'logId').catch(error => { throw error; });
        let log = await db.find(config.jd.log, { logId: max[0].logId }).catch(error => { throw error; });

        if (!log[0].end) {
            let err = await db.find(config.jd.error, { logId: max[0].logId }).catch(error => { throw error; });
            if (err.length > 0) {
                output = { 'result': false, 'log': log[0],'error':err[0] };//没有end但是有错误记录
            }
            else{
                output = { 'result': true, 'log': log[0] };//没有end，没错误=>还在执行
            }
        }
        else{
            output = { 'result': false, 'log': log[0] };//有end=>执行完毕
        }
    }
    catch (error) {
        output = { 'result': 'error', 'error': error.toString() };
    }
    return (ctx.response.body = JSON.stringify(output));
});
router.post('/mongo/shops/isCrawling', async (ctx) => {
    let output = {};
    try {
        let max = await db.groupMax(config.jd.shopsLog, { operation: 'crawl' }, 'logId').catch(error => { throw error; });
        let log = await db.find(config.jd.shopsLog, { logId: max[0].logId }).catch(error => { throw error; });

        if (!log[0].end) {
            let err = await db.find(config.jd.shopsError, { logId: max[0].logId }).catch(error => { throw error; });
            if (err.length > 0) {
                output = { 'result': false, 'log': log[0],'error':err[0] };//没有end但是有错误记录
            }
            else{
                output = { 'result': true, 'log': log[0] };//没有end，没错误=>还在执行
            }
        }
        else{
            output = { 'result': false, 'log': log[0] };//有end=>执行完毕
        }
    }
    catch (error) {
        output = { 'result': 'error', 'error': error.toString() };
    }
    return (ctx.response.body = JSON.stringify(output));
});
module.exports = router